import { getDataTypeOptionsReq } from '@/service/modules/data-manage'
import { ColumnInfo, IndexInfo } from '@/service/modules/data-manage/types'
import { SelectOption } from 'naive-ui'
import { reactive } from 'vue'

export function useTable() {
  const state = reactive({
    dataTypeOptions: Array<SelectOption>(),
    loading: false
  })
  const createTableEntity = reactive({
    datasourceId: 0,
    dbName: '',
    reason: '',
    mode: 'visual',
    ddl: '',
    tableInfo: {
      tableName: '',
      tableComment: '',
      ddl: '',
      columns: Array<ColumnInfo>(),
      indexs: Array<IndexInfo>()
    },
    previewData: '{}'
  })
  const getDataTypeOptions = async (databaseId: number) => {
    if (state.loading) return
    state.loading = true
    const res = await getDataTypeOptionsReq({ databaseId: databaseId })
    state.loading = false
    if (res.resp_code === 0) {
      state.dataTypeOptions.splice(0)
      res.data.forEach((element: string) => {
        state.dataTypeOptions.push({
          label: element,
          value: element
        })
      })
    }
  }

  const onOperationClick = (
    index: number,
    type:
      | 'insertField'
      | 'removeField'
      | 'moveUpField'
      | 'moveDownField'
      | 'insertIndex'
      | 'removeIndex'
  ) => {
    switch (type) {
      case 'insertField':
        createTableEntity.tableInfo.columns.splice(index + 1, 0, {
          columnName: 'new_column',
          dataType: state.dataTypeOptions[0].value as string,
          args: '',
          isNotNull: false,
          defVal: '',
          isPrimkey: false,
          isPartition: false,
          columnComment: '',
          previewData: ''
        })
        break
      case 'removeField':
        createTableEntity.tableInfo.columns.splice(index, 1)
        break
      case 'moveUpField':
        if (index === 0) return
        const up1 = createTableEntity.tableInfo.columns[index - 1]
        const down1 = createTableEntity.tableInfo.columns[index]
        createTableEntity.tableInfo.columns[index - 1] = down1
        createTableEntity.tableInfo.columns[index] = up1
        break
      case 'moveDownField':
        if (index === createTableEntity.tableInfo.columns.length - 1) return
        const up2 = createTableEntity.tableInfo.columns[index]
        const down2 = createTableEntity.tableInfo.columns[index + 1]
        createTableEntity.tableInfo.columns[index] = down2
        createTableEntity.tableInfo.columns[index + 1] = up2
        break
      case 'insertIndex':
        createTableEntity.tableInfo.indexs.splice(index + 1, 0, {
          indexName: 'new_index',
          columns: '',
          isUnique: false
        })
        break
      case 'removeIndex':
        createTableEntity.tableInfo.indexs.splice(index, 1)
        break
    }
  }

  return {
    state,
    createTableEntity,
    getDataTypeOptions,
    onOperationClick
  }
}
